import { useStore } from "@/util/hooks";
import { DraggableModal } from "./drag-modal";
import { FormModalProps, ModalStore } from "./inteface";
import { useEffect } from "react";

function switchTitle(title: string, type: ModalStore<any>["type"]) {
  if (type === "add") return `新增${title}`;
  else if (type === "update") return `更新${title}`;
  return `${title}详情`;
}

export function FormModal<T = any>({
  title,
  fullTitle,
  atom,
  form,
  autoSetField = true,
  children,
  afterClose: customAfterClose,
  ...props
}: FormModalProps<T>) {
  const store = useStore(atom);
  const { value } = store;

  function onClose() {
    store.updateStore({
      open: false,
    });
  }

  function afterClose() {
    form.resetFields();
    store.updateStore({
      record: undefined,
    });
    customAfterClose?.();
  }

  useEffect(() => {
    if (autoSetField && value.open && value.record) {
      form.setFieldsValue({
        ...value.record,
      });
    }
  }, [value.open, value.record, form]);

  const titleText = fullTitle || switchTitle(title || "", value.type);
  return (
    <DraggableModal
      {...props}
      visible={value.open}
      title={titleText}
      onCancel={onClose}
      mountOnEnter={false}
      alignCenter={false}
      afterClose={afterClose}
      closable={true}
    >
      {children}
    </DraggableModal>
  );
}
